package constant.milk.toilet.info;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import constant.milk.toilet.R;
import constant.milk.toilet.SuperActivity;
import constant.milk.toilet.bean.TimerData;
import constant.milk.toilet.broadcast.PushBroadcast;
import constant.milk.toilet.database.DbInsertQuery;
import constant.milk.toilet.database.DbSelectQuery;
import constant.milk.toilet.dialog.MilkDialog;
import constant.milk.toilet.dialog.MilkTimeDialog;
import constant.milk.toilet.dialog.MilkTimeDialog.TimeCollBank;
import constant.milk.toilet.util.MilkUtil;

public class InsertActivity extends SuperActivity
{
	private TextView preView;
	private TextView titleTextView;
	
	private TextView todayTitleTextView;
	private TextView todayTextView;
	
	private TextView costTimeTitleTextView;
	private View costTimeView;
	private TextView startTimeTextView;
	private TextView endTimeTextView;
	
	private TextView termTimeTitleTextView;
	private View termTimeView;
	private TextView termTimeTextView;
	
	private View saveView;
	private TextView saveTitleTextView;
	
	private int year;
	private int month;
	private int day;
	
	private long startMTime;
	private long endMTime;
	
	private int hour;
	private int min;
	
	private MilkTimeDialog timeDialog;
	
	private int hourTerm;
	private int minTerm;
	private int secTerm;
	
	private MilkDialog okDialog;
	private MilkDialog failDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.insert_activity);
		
		setFindViewId();
		setOnClick();
		setData();
	}
	
	@Override
	protected void setFindViewId()
	{
		preView = (TextView) findViewById(R.id.insertPreTextView);
		titleTextView = (TextView) findViewById(R.id.insertTitleTextView);
		
		todayTitleTextView = (TextView) findViewById(R.id.insertTodayTitleTextView);
		todayTextView = (TextView) findViewById(R.id.insertTodayTextView);
		
		costTimeTitleTextView = (TextView) findViewById(R.id.insertCostTimeTitleTextView);
		costTimeView = findViewById(R.id.insertCostTimeView);
		startTimeTextView = (TextView) findViewById(R.id.insertStartTimerTextView);
		endTimeTextView = (TextView) findViewById(R.id.insertEndTimerTextView);
		
		termTimeTitleTextView = (TextView) findViewById(R.id.insertTermTimeTitleTextView);
		termTimeView = findViewById(R.id.insertTermTimeView);
		termTimeTextView = (TextView) findViewById(R.id.insertTermTimeTextView);
		
		saveTitleTextView = (TextView) findViewById(R.id.insertSaveTextView);
		saveView = findViewById(R.id.insertSaveView);
	}

	@Override
	protected void setOnClick()
	{
		preView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		
		costTimeView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				timeDialog = new MilkTimeDialog(superContext, 
						new TimeCollBank()
						{
							@Override
							public void getTime(int hourTime, int minTime, int secTime)
							{
								Calendar calS = Calendar.getInstance();
								calS.set(year, month, day, hourTime, minTime);
								startMTime = calS.getTimeInMillis();
								
								Calendar calT = Calendar.getInstance();
								calT.set(year, month, day, hourTime, minTime);
								calT.add(Calendar.HOUR_OF_DAY, hourTerm);
								calT.add(Calendar.MINUTE, minTerm);
								calT.add(Calendar.SECOND, secTerm);
								
								endMTime = calT.getTimeInMillis();
								
								Calendar calE = Calendar.getInstance();
								calE.setTimeInMillis(endMTime);
								
								hour = calS.get(Calendar.HOUR_OF_DAY);
								min = calS.get(Calendar.MINUTE);
								
								startTimeTextView.setText(MilkUtil.getTime(hour, min));
								endTimeTextView.setText(MilkUtil.getTime(calE.get(Calendar.HOUR_OF_DAY), calE.get(Calendar.MINUTE)));
							}
						}, 
						hour, min, 0);
				
				timeDialog.show();
			}
		});

		termTimeView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				timeDialog = new MilkTimeDialog(superContext, 
						new TimeCollBank()
						{
							@Override
							public void getTime(int hourTime, int minTime, int secTime)
							{
								Calendar calE = Calendar.getInstance();
								calE.setTimeInMillis(startMTime);
								calE.add(Calendar.HOUR_OF_DAY, hourTime);
								calE.add(Calendar.MINUTE, minTime);
								calE.add(Calendar.SECOND, secTime);
								
								endMTime = calE.getTimeInMillis();
								
								hourTerm = hourTime;
								minTerm = minTime;
								secTerm = secTime;
								
								startTimeTextView.setText(MilkUtil.getTime(hour, min));
								endTimeTextView.setText(MilkUtil.getTime(calE.get(Calendar.HOUR_OF_DAY), calE.get(Calendar.MINUTE)));
								termTimeTextView.setText(MilkUtil.getTimeStr2(hourTime, minTime, secTime));
							}
						}, 
						hourTerm, minTerm, secTerm);
				
				timeDialog.show();
			}
		});
		
		saveView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (hourTerm == 0 && minTerm == 0 && secTerm == 0)
				{
					okDialog = new MilkDialog(superContext, 
							"경과시간이 0초 입니다. 제대로 입력 해주세요.", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									okDialog.dismiss();
								}
							}, 
							null);
					okDialog.setLeftTitle("확인");
					okDialog.show();
					
					return;
				}
				
				if (setSaveData())
				{
					okDialog = new MilkDialog(superContext, 
							"저장에 성공 하였습니다.", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									okDialog.dismiss();
									setResult(Activity.RESULT_OK);
									finish();
								}
							}, 
							null);
					okDialog.setLeftTitle("확인");
					okDialog.show();
				}
				else
				{
					failDialog = new MilkDialog(superContext, 
							"저장에 실패 하였습니다. 개발자에게 문의 해주세요.", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									failDialog.dismiss();
								}
							}, 
							null);
					failDialog.setLeftTitle("확인");
					failDialog.show();
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		titleTextView.setTextColor(Color.WHITE);
		todayTitleTextView.setTextColor(Color.WHITE);
		costTimeTitleTextView.setTextColor(Color.WHITE);
		termTimeTitleTextView.setTextColor(Color.WHITE);
		saveTitleTextView.setTextColor(Color.WHITE);
		
		titleTextView.setTextSize(TEXT_SIZE + 2);
		
		Calendar cal = Calendar.getInstance();
		hour = cal.get(Calendar.HOUR_OF_DAY);
		min = cal.get(Calendar.MINUTE);
		
		Intent intent = getIntent();
		year = intent.getIntExtra(InfoActivity.YEAR, cal.get(Calendar.YEAR));
		month = intent.getIntExtra(InfoActivity.MONTH, cal.get(Calendar.MONTH));
		day = intent.getIntExtra(InfoActivity.DAY, cal.get(Calendar.DAY_OF_MONTH));
		
		todayTextView.setText(MilkUtil.getDateCom(year, month+1, day));
		
		startMTime = cal.getTimeInMillis();
		endMTime = cal.getTimeInMillis();
		
		startTimeTextView.setText(MilkUtil.getTime(hour, min));
		endTimeTextView.setText(MilkUtil.getTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)));
		
		hourTerm = 0;
		minTerm = 0;
		secTerm = 0;
		
		termTimeTextView.setText(MilkUtil.getTimeStr2(hourTerm, minTerm, secTerm));
	}
	
	private boolean setSaveData()
	{
		DbInsertQuery query = null;
		DbSelectQuery select = null;
		
		try
		{
			query = new DbInsertQuery(superContext, superDb);
			select = new DbSelectQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("year", year + "");
			map.put("month", month + "");
			map.put("day", day + "");
			map.put("starttime", startMTime + "");
			
			endMTime = endMTime - startMTime;
			
			map.put("term", endMTime + "");
			
			query.insertTimer(map);
			
			Calendar cal = Calendar.getInstance();
			int toYear = cal.get(Calendar.YEAR);
			int toMonth = cal.get(Calendar.MONTH);
			int toDay = cal.get(Calendar.DAY_OF_MONTH);
			
			if (toYear == year && toMonth == month && toDay == day)
			{
				ArrayList<TimerData> list = select.getTimerStartTime(startMTime);
				
				if (list.size() < 1)
				{
					SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);
					
					int alarmPush = p.getInt(getString(R.string.prefPushAlarm), 1);
					
					if (alarmPush > 1)
					{
						Intent intent = new Intent(superContext, PushBroadcast.class);    
						PendingIntent sender = PendingIntent.getBroadcast(superContext, 1, intent, 
								PendingIntent.FLAG_CANCEL_CURRENT);
						
				        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
				        manager.cancel(sender);
				        
				        int version = Build.VERSION.SDK_INT;
						
						if (version >= 19)
						{
							manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (24 * 60 * 60000), sender);
						}
						else
						{
							manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (24 * 60 * 60000), sender);
						}
				        
				        SharedPreferences.Editor e = p.edit();
				        
				        e.putInt(getString(R.string.prefPushAlarm), 1);
				        e.commit();
					}
				}
			}
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
}
